const BaseRest = require('./base.js');

module.exports = class extends BaseRest {
  constructor(ctx) {
    super(ctx);
    this.modelInstance = this.model('content');
  }

  /**
   * 获取内容
   * @return {[type]} [description]
   */
  async getAction() {
    let data;
    const map = {};
    // 获取详情
    if (this.getId()) {
      map.slug = this.id;
      if (think.isEmpty(this.userInfo)) {
        map.status = 99;
      }
      data = await this.modelInstance.where(map).find();
      // 增加阅读量
      if (!this.userInfo) {
        this.modelInstance.where(map).increment('view');
      }
      return this.success(data);
    }
    // 获取列表
    const type = this.get('type') || 'default';
    // 归档
    if (type === 'archives') {
      data = await this.modelInstance.where({ status: 99 }).order('create_time desc').fieldReverse('content,markdown').select();
      return this.success(data);
    }
    // 热门文章
    if (type === 'hot') {
      data = await this.modelInstance.where({ status: 99 }).order('view desc').limit(10).field('title,slug,view').select();
      return this.success(data);
    }
    // 是否获取全部
    const all = this.get('all');
    if (!all || think.isEmpty(this.userInfo)) {
      map.status = 99;
    }
    // 关键词
    const key = this.get('key');
    if (key) {
      map['title|description'] = ['like', '%' + key + '%'];
    }

    // 内容类型
    const contentType = this.get('contentType') || 'post';
    map['type'] = contentType;
    // 页码
    const page = this.get('page') || 1;
    // 每页显示数量
    const pageSize = this.get('pageSize') || 5;
    data = await this.modelInstance.where(map).page(page, pageSize).order('create_time desc').fieldReverse('content,markdown').countSelect();

    // console.log(JSON.stringify(data));

    // {
    //   "errno": 0,
    //   "errmsg": "",
    //   "data": {
    //       "count": 6,
    //       "totalPages": 2,
    //       "pageSize": 5,
    //       "currentPage": 1,
    //       "data": [...],
    //   }
    // }

    return this.success(data);
  }
};
